package com.ets.cert.webapp.controller;

import com.ets.cert.Constants;
import com.ets.cert.service.NewsManager;
import com.ets.cert.model.News;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class NewsController {
	@Autowired
    private NewsManager newsManager;
   

    @RequestMapping(value="/admin/news/preAdd", method = RequestMethod.GET)
    public String preAdd() {
    	return "/WEB-INF/pages/admin/addNews.jsp";
    }
    
    @ResponseBody
    @RequestMapping(value="/admin/news/add", method = RequestMethod.POST)
    public String add(News news) {
    	try {
    		newsManager.save(news);
    		return Constants.SUCCESS;
    	} catch (Throwable t) {
    		return Constants.FAIL + t.getMessage();
    	}
    }
    
    @ResponseBody
    @RequestMapping(value="/admin/news/delete", method = RequestMethod.GET)
    public String delete(@RequestParam("id") Long id) {
    	try {
    		newsManager.remove(id);
    		return Constants.SUCCESS;
    	} catch (Throwable t) {
    		return Constants.FAIL + t.getMessage();
    	}
    }
    
    @RequestMapping(value="/admin/news/edit", method = RequestMethod.GET)
    public String edit(Model model, @RequestParam("id") Long id) {
    	model.addAttribute("cert", newsManager.get(id));
    	return "/WEB-INF/pages/admin/editNews.jsp";
    }
    
    @RequestMapping(value="/admin/news/list", method = RequestMethod.GET)
    public String list(Model model) {
    	model.addAttribute("newsList", newsManager.getAll());
    	return "/WEB-INF/pages/admin/newsList.jsp";
    }
    
    @RequestMapping(value="/news/index", method = RequestMethod.GET)
    public String indexList(Model model) {
    	model.addAttribute("newsList", newsManager.getAll());
    	return "json";
    }
    
    @RequestMapping(value="/news/news", method = RequestMethod.GET)
    public String newsDetail(Model model, @RequestParam(required=false, value="id") Long id) {
    	if (id == null) {
    		model.addAttribute("newsList", newsManager.getAll());
    		return "/WEB-INF/pages/public/newsList.jsp";
    	}
    	else {
	    	model.addAttribute("news", newsManager.get(id));
	    	return "/WEB-INF/pages/public/newsDetail.jsp";
    	}
    }
    
    @RequestMapping(value="/news/newsDetail", method = RequestMethod.GET)
    public String news(Model model, @RequestParam("id") Long id) {
    	model.addAttribute("news", newsManager.get(id));
    	return "json";
    }
}
